<template>
  <div class="change-machine-container">
    <div class="header">
      <h2>设备故障报告</h2>
    </div>
    
    <div class="content">
      <el-card class="main-card">
        <div class="card-content">
          <el-alert
            title="如果您当前的设备出现故障，请点击下方按钮申报"
            type="info"
            :closable="false"
            show-icon
          />
          
          <div class="description">
            <p>机器故障申报将会：</p>
            <ul>
              <li>向监考老师发送您的机器故障通知</li>
              <li>暂停您当前的考试</li>
              <li>等待老师批准后，您可以在新机器上继续考试</li>
            </ul>
          </div>
          
          <div class="action-btn">
            <el-button 
              type="danger" 
              size="large" 
              :loading="submitting"
              @click="confirmChangeMachine"
            >
              申报机器故障
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 等待批准对话框 -->
    <el-dialog
      v-model="waitingApprovalVisible"
      title="等待批准"
      width="360px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="waiting-content">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p>已向监考老师发送机器故障申报，请等待批准...</p>
        <p class="hint">批准后系统将自动退出登录，请前往新设备重新登录继续考试</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { reportMachineFault, getApprovalStatus } from '@/api/student/changeMachine'
import { useUserStore } from '@/stores'
import { useExamStore } from '@/stores/modules/exam-student'

const router = useRouter()
const userStore = useUserStore()
const examStore = useExamStore()

const submitting = ref(false)
const waitingApprovalVisible = ref(false)
let websocket = null

// 确认机器故障
const confirmChangeMachine = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要申报机器故障吗？这将暂停您的考试，并等待老师批准更换设备。',
      '申报确认',
      {
        confirmButtonText: '确认申报',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    submitMachineFault()
  } catch {
    // 用户取消，不做操作
  }
}

// 提交机器故障
const submitMachineFault = async () => {
  if (!examStore.currentExam) {
    ElMessage.error('没有正在进行的考试')
    return
  }
  
  submitting.value = true
  
  try {
    const studentPaperId = examStore.currentExam.id
    await reportMachineFault(studentPaperId)
    
    // 显示等待批准对话框
    waitingApprovalVisible.value = true
    
    // 尝试连接WebSocket等待批准通知
    try {
      connectWebSocket(studentPaperId)
    } catch (wsError) {
      console.error('WebSocket连接失败，启用轮询备用方案:', wsError)
      // WebSocket连接失败时使用轮询备用方案
      approvalInterval = checkApprovalStatus(studentPaperId)
    }
  } catch (error) {
    console.error('申报机器故障失败:', error)
    ElMessage.error('申报失败，请重试或联系监考老师')
    submitting.value = false
  }
}

// 连接WebSocket
const connectWebSocket = (studentPaperId) => {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const baseUrl = process.env.VUE_APP_WS_URL || window.location.host
  const wsUrl = `${protocol}//${baseUrl}/ws/change-machine/${studentPaperId}`
  
  websocket = new WebSocket(wsUrl)
  
  websocket.onopen = () => {
    console.log('WebSocket连接已建立')
  }
  
  websocket.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      
      if (data.type === 'approval' && data.approved) {
        handleApproval()
      }
    } catch (error) {
      console.error('WebSocket消息解析错误:', error)
    }
  }
  
  websocket.onerror = (error) => {
    console.error('WebSocket错误:', error)
    ElMessage.error('连接服务器失败，启用轮询方式检查审批状态')
    
    // WebSocket出错时使用轮询备用方案
    if (!approvalInterval) {
      approvalInterval = checkApprovalStatus(studentPaperId)
    }
  }
  
  websocket.onclose = () => {
    console.log('WebSocket连接已关闭')
    
    // WebSocket关闭且不是因为组件卸载引起的，使用轮询备用方案
    if (waitingApprovalVisible.value && !approvalInterval) {
      approvalInterval = checkApprovalStatus(studentPaperId)
    }
  }
}

// 处理批准消息
const handleApproval = () => {
  ElMessage.success('机器故障申报已获批准，正在退出登录...')
  
  // 延迟一下让用户看到成功消息
  setTimeout(() => {
    // 退出登录
    userStore.logout()
    
    // 清除考试数据
    examStore.clearAllExamData()
    
    // 跳转到登录页
    router.push('/login')
  }, 1500)
}

// 备用方案：轮询检查是否获得批准
const checkApprovalStatus = (studentPaperId) => {
  // 如果WebSocket不可用，可以实现一个轮询方法
  const checkInterval = setInterval(async () => {
    try {
      const { data } = await getApprovalStatus(studentPaperId)
      if (data.approved) {
        clearInterval(checkInterval)
        handleApproval()
      }
    } catch (error) {
      console.error('检查批准状态失败:', error)
    }
  }, 5000) // 每5秒检查一次
  
  // 保存计时器引用，以便后续清除
  return checkInterval
}

// 组件卸载时关闭WebSocket连接和清除定时器
let approvalInterval = null
onUnmounted(() => {
  if (websocket) {
    websocket.close()
    websocket = null
  }
  
  // 清除轮询定时器
  if (approvalInterval) {
    clearInterval(approvalInterval)
    approvalInterval = null
  }
})
</script>

<style scoped>
.change-machine-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.content {
  display: flex;
  justify-content: center;
}

.main-card {
  width: 100%;
  max-width: 600px;
  border-radius: 8px;
}

.card-content {
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.description {
  margin: 30px 0;
  text-align: left;
  width: 100%;
}

.description p {
  font-weight: bold;
  margin-bottom: 10px;
}

.description ul {
  padding-left: 20px;
}

.description li {
  line-height: 1.8;
}

.action-btn {
  margin-top: 20px;
}

.waiting-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.loading-icon {
  font-size: 40px;
  color: #409EFF;
  margin-bottom: 20px;
  animation: rotate 2s linear infinite;
}

.hint {
  font-size: 14px;
  color: #909399;
  margin-top: 10px;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 